﻿using System.Web.Mvc;

using Whoever.Framework.Enum;
using Whoever.Framework.CustomException;
using Whoever.Framework.Utils;

using Whoever.Patterns.MVC.Models;

namespace Whoever.Patterns.MVC.Filters
{
    public class AJAXExceptionHandler : FilterAttribute, IExceptionFilter
    {
        public AJAXExceptionHandler()
        {
        }

        public AJAXExceptionHandler(AJAXResponse customResponse)
        {
            CustomResponse = customResponse;
        }

        private AJAXResponse CustomResponse { get; set; }

        public void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            string message;
            MessageType messageType;

            if (filterContext.Exception is BusinessException)
            {
                var businessException = (BusinessException)filterContext.Exception;

                message = businessException.Message;
                messageType = businessException.MessageType;
            }
            else
            {
                message = Localized.Message("Exception", MessageType.Error);
                messageType = MessageType.Error;
            }

            filterContext.Result = new JsonResult
            {
                Data = CustomResponse ?? new AJAXResponse { Success = false, Message = message, MessageType = messageType },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}
